﻿// USocket.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//
#define _WINSOCK_DEPRECATED_NO_WARNINGS
#include "USocket.h"
#include <iostream>
int USocket::m_instCount = 0;
USocket::USocket()
{
	if (m_instCount == 0)
	{
		if (WSAStartup(MAKEWORD(2, 2), &wsaData) != 0)
			return;
	}
	m_instCount++;
}


void USocket::OnReceive()
{
	isRunning = true;
	while (isRunning) {
		int clntAdrSz = sizeof(sockAddr);
		//接收数据报
		int strLen = recvfrom(sock, buff, buffsize, 0,
			(struct sockaddr*)&sockAddr, &clntAdrSz);
		fRecv(mergedData, strLen);
		cout << "recv:" << "strLen" << endl;
	}

}

void USocket::Close()
{
	if (sock == INVALID_SOCKET)
		OnError("accept() error!");
	closesocket(sock);
	m_instCount--;
	isRunning = false;
	if (m_instCount == 0)
	{
		WSACleanup();
	}
}

void USocket::Send(void* data, int len)
{
	send(sock, (const char*)data, len, 0);
}

void UClientSocket::Init(std::string ip, int port)
{
	sock = socket(PF_INET, SOCK_DGRAM, 0);
	if (INVALID_SOCKET == sock) {
		OnError("UDP socket creation error.");
	}

	memset(&sockAddr, 0, sizeof(sockAddr));
	sockAddr.sin_family = AF_INET;
	sockAddr.sin_addr.s_addr = inet_addr(ip.c_str());
	sockAddr.sin_port = htons(port);
	connect(sock, (SOCKADDR*)&sockAddr, sizeof(sockAddr));
	std::thread th(&UClientSocket::OnReceive, this);
	th.detach();
}
void UServerSocket::Init(int port)
{
	sock = socket(AF_INET, SOCK_DGRAM, 0);
	if (sock == INVALID_SOCKET)
		OnError("socket() error!");

	memset(&sockAddr, 0, sizeof(sockAddr));

	sockAddr.sin_family = AF_INET;
	sockAddr.sin_addr.s_addr = htonl(INADDR_ANY);
	sockAddr.sin_port = htons(port);

	if (::bind(sock, (SOCKADDR *)&sockAddr, sizeof(sockAddr)) == -1)
		OnError("bind() error!");

	std::thread th(&UServerSocket::OnReceive, this);
	th.detach();
}